import React, { PureComponent, Fragment } from 'react'
import { connect } from 'dva';
import DocumentTitle from 'react-document-title';
import isEqual from 'lodash/isEqual';
import memoize from "memoize-one";
import pathToRegexp from 'path-to-regexp';
import { formatMessage } from 'umi/locale';
import { SITE_NAME } from '@/setting';


class BasicLayout extends PureComponent {

  constructor(props){
    super(props);
    this.getPageTitle=memoize(this.getPageTitle,isEqual);
    this.matchParamsPath=memoize(this.matchParamsPath,isEqual);
  }

  componentDidMount () {
    const {
      dispatch,
    } = this.props;
    dispatch({
      type: 'menu/getMenuData',
    });
  }

 
  getPageTitle = (pathname, breadcrumbNameMap) => {
    const currRouterData = this.matchParamsPath(pathname, breadcrumbNameMap);
    if (!currRouterData) {
      return  SITE_NAME;
    }
    const pageName = formatMessage({
      id:  currRouterData.locale || currRouterData.name,
      defaultMessage: currRouterData.name,
    });

    return `${pageName} - ${SITE_NAME}`;
  };

  matchParamsPath = (pathname, breadcrumbNameMap) => {
    const pathKey = Object.keys(breadcrumbNameMap).find(key => pathToRegexp(key).test(pathname));
    return breadcrumbNameMap[pathKey];
  };

  render () {
    const {
      location: { pathname },
      breadcrumbNameMap,
      children,
      route: { routes },
    } = this.props;
    return (
      <Fragment>
        <DocumentTitle title={this.getPageTitle(pathname, breadcrumbNameMap)}>
          { children }
        </DocumentTitle>
      </Fragment>
    );
  }
}

export default connect(({ global, menu }) => ({
  collapsed: global.collapsed,
  menuData: menu.menuData,
  breadcrumbNameMap: menu.breadcrumbNameMap,
}))(BasicLayout);
